<style lang="less" scoped>
    @import '../../styles/common.less';
    @import '../../styles/loading.less';
    @import 'daren.less';
</style>

<template>
    <div>
        <Row style="font-size: 15px;">

            姓名：<Input v-model="queryCon.name" clearable style="width: 15%"></Input>
            <span @click="loadList"><Button type="primary" icon="android-search">查询</Button></span>
        </Row>
        <Row>
            <span @click="showAdd"><Button type="primary" icon="android-add">新增</Button></span>
        </Row>
        <div class="main-table">
            <Table border :columns="columns" :data="data"></Table>
        </div>
        <div class="pagination">
            <Page :total="total" size="small" :page-size="pageSize" :current.sync="pageIndex" @on-change="loadList" show-total show-elevator></Page>
        </div>
        <Modal
                v-model="viewModalVisible"
                title="达人信息"
                @on-ok="viewModalVisible = false"
                @on-cancel="viewModalVisible = false"
                width="35%">
            <Form :model="formData" :label-width="90">
                <!--<FormItem label="访问地址">-->
                    <!--<div class="conts">-->
                        <!--http://www.ziranm.cn/wxOAuth?appId={{formData.platformManageAppid}}&callBackUrl=actdetail.html&typeId={{formData.id}}-->
                    <!--</div>-->
                <!--</FormItem>-->
                <FormItem label="姓名">
                    <div class="conts">{{formData.name}}</div>
                </FormItem>
                <FormItem label="联系电话">
                    <div class="conts">{{formData.phone}}</div>
                </FormItem>
                <FormItem label="录入时间">
                    <div class="conts">{{formData.inputTime}}</div>
                    <!--<DatePicker type="date" v-model="formData.inputTime" @on-change="formData.discounttime=$event"></DatePicker>-->
                </FormItem>
                <FormItem label="头像">
                    <div class="admin-upload-list" :key="formData.imgUrl">
                        <Modal v-model="showImgDetail" title="查看图片" @on-cancel="closeImgDetail">
                            <img :src="formData.imgUrl" width="100%" height="100%">
                            <div slot="footer">
                                <Button type="primary" @click="closeImgDetail">确定</Button>
                            </div>
                        </Modal>
                        <template>
                            <img :src="formData.imgUrl">
                            <div class="admin-upload-list-cover">
                                <Icon type="ios-eye-outline" @click.native="openImgDetail"></Icon>
                            </div>
                        </template>
                    </div>
                </FormItem>
                <FormItem label="介绍">
                    <div class="conts">{{formData.introduce}}</div>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="saveModalVisible" :title="(formData.id ? '修改' : '新增') + '达人'" width="40%" @on-cancel="destroyed">
            <Form :model="formData" :label-width="125">
                <FormItem label="姓名">
                    <Input v-model="formData.name" clearable ></Input>
                </FormItem>
                <FormItem label="联系电话">
                    <Input v-model="formData.phone" clearable ></Input>
                </FormItem>
                <FormItem label="头像">
                    <div class="admin-upload-list" v-for="item in uploadList" :key="item.url">
                        <Modal v-model="showImg" title="查看图片" @on-cancel="closeImg">
                            <img :src="item.url" width="100%" height="100%">
                            <div slot="footer">
                                <Button type="primary" @click="closeImg">确定</Button>
                            </div>
                        </Modal>
                        <template v-if="item.status === 'finished'">
                            <img :src="item.url">
                            <div class="admin-upload-list-cover">
                                <Icon type="ios-eye-outline" @click.native="openImg"></Icon>
                                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                            </div>
                        </template>
                        <template v-else>
                            <Progress v-if="item.showProgress" :percent="item.percentage" status="active" hide-info></Progress>
                        </template>
                    </div>
                    <Upload
                            ref="upload"
                            name="file"
                            :action="SERVER_HOST + 'upload/uploadFile'"
                            :format="['jpg', 'png', 'jpeg', 'gif', 'bmp', 'svg']"
                            :max-size="2048"
                            :on-exceeded-size="handleMaxSize"
                            :on-format-error="handleFormatError"
                            :on-success="handleSuccess"
                            :before-upload="handleBeforeUpload"
                            type="drag"
                            multiple
                            :show-upload-list="false"
                            style="display: inline-block;width:58px;"
                    >
                        <div style="width: 58px;height:58px;line-height: 58px;">
                            <Icon type="camera" size="20"></Icon>
                        </div>
                    </Upload>
                </FormItem>
                <FormItem label="介绍">
                    <!--<textarea class='tinymce-textarea' id="introduce" v-model="formData.introduce"></textarea>-->
                    <!--<textarea id="introduce"  v-model="formData.introduce" ></textarea>-->
                    <Input id="introduce"  v-model="formData.introduce" type="textarea" :rows="4" width="10"></Input>
                </FormItem>
            <!--<FormItem label="介绍">-->
                <!--<textarea class='tinymce-textarea' id="introduce" v-model="formData.introduce"></textarea>-->
            <!--</FormItem>-->
            </Form>

            <div slot="footer">
                <Button type="primary" @click="activitySave">保存</Button>
                <Button type="ghost" style="margin-left: 8px" @click="destroyed">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import CONSTANTS from '@/config/constants';
    import tinymce from 'tinymce';

    export default {
        name: 'exportable-table',
        data () {
            return {
                columns: [{
                    title: '序号',
                    key: 'rownum',
                    width: 60,
                    align: 'center'
                }, {
                    title: '姓名',
                    key: 'name'
                },{
                    title: '录入时间',
                    key: 'inputTime'
                },{
                    title: '介绍',
                    key: 'introduce'
                },   {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    align: 'center',
                    render: (h, params) => {
                        let isShow = 'none';
                        if(params.row.releases == 'NO'){
                            isShow = 'inline';
                        }  return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.detail(params.row.id);
                                    }
                                }
                            }, '详情'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showEdit(params.row);
                                    }
                                }
                            }, '修改'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.delete(params.row.id)
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }],
                data: [],
                formData: {},
                viewModalVisible: false,
                saveModalVisible: false,
                priceModalVisible: false,
                showImgDetail: false,
                showImg: false,
                isSelect:true,
                isInput:false,

                total: 0,
                pageIndex: 1,
                pageSize: 10,
                queryCon:{
                    inputTime:'',
                    name:'',
                    introduce:'',
                    id:''
                },
                uploadList:[],
                id:'',
                imgUrl: '',
                SERVER_HOST: CONSTANTS.SERVER_HOST
            };
        },
        mounted() {
            this.loadList();
        },
        methods: {
            loadList() {
                util.ajax.post('/busine/daren/list', util.toFormData({
                    page: this.pageIndex,
                    size: this.pageSize,
                    name: this.queryCon.name,
                })).then(res => {
                    var lists = res.data.data.pageInfo.list;
                    for (var i = 0; i < lists.length; i++) {
                        lists[i]['inputTime'] = this.getDate(lists[i].inputTime);
                    }
                    this.data = res.data.data.pageInfo.list;
                    this.total = res.data.data.pageInfo.total;
                });
            },
            detail(id) {
                let _this = this;
                util.ajax.post( '/busine/daren/detail', util.toFormData({
                    id: id
                })).then(res => {
                    if (res.data.data) {
                        var li = res.data.data;

                        li['inputTime'] = this.getDate(li.inputTime);
                        li['imgUrl'] = CONSTANTS.SERVER_HOST + li.cover;
                        _this.formData = res.data.data;
                        _this.viewModalVisible = true;
                    } else {
                        _this.$Modal.error({
                            title: '警告',
                            content: '出错了'
                        });
                    }
                });
            },
            showAdd() {
                this.formData = {};
                this.saveModalVisible = true;
                this.timeList = 1;
                this.uploadList = [];
            },
            showEdit(obj) {
                this.timeList = [];
                this.formData = {};
                util.ajax.post('/busine/daren/detail', util.toFormData({
                    id: obj.id
                })).then(res => {
                    if (res.data.data) {
                        var li = res.data.data;
                        li['inputTime'] = this.getDate(li.inputTime);
                        this.imgUrl = li.cover;
                        if (li.cover) {
                            this.uploadList = [{
                                status: 'finished',
                                showProgress: true,
                                url: CONSTANTS.SERVER_HOST + li.cover
                            }];
                        } else {
                            this.uploadList = [];
                        }


                        this.formData = res.data.data;
                        this.saveModalVisible = true;
                    } else {
                        this.$Modal.error({
                            title: '警告',
                            content: '出错了'
                        });
                    }
                });
            },
            activitySave() {
                let formData = {};
                for (let key in this.formData) {
                    formData[key] = this.formData[key];
                }
                util.ajax.post('/busine/daren/save', util.toFormData(formData)).then(res => {
                    if (res.data.message === 'SUCCESS') {
                        this.saveModalVisible = false;
                        this.$Message.success('保存成功！');
                        this.pageIndex = 1;
                        this.loadList();
                    } else {
                        this.$Message.warning(res.data.message || '未知错误！');
                    }
                });
            },
            delete(id) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定删除？</p>',
                    onOk: () => {
                        util.ajax.post('/busine/daren/delete', util.toFormData({
                            id: id
                        })).then(res => {
                            if (res.data.message === 'SUCCESS') {
                                this.$Message.success('删除成功！');
                                this.loadList();
                            }
                        });
                    },
                    onCancel: () => {
                    }
                });
            },
            getDate(data) {
                let myDate;

                if (data instanceof Date){
                    myDate = data;
                } else if (typeof(data) == 'number') {
                    myDate = new Date(data);
                } else {
                    return data;
                }

                let Y = myDate.getFullYear(),
                    M = myDate.getMonth() + 1,
                    D = myDate.getDate(),
                    H = myDate.getHours(),
                    Min = myDate.getMinutes(),
                    S = myDate.getSeconds();

                if (M < 10) {
                    M = '0' + M;
                }
                if (D < 10) {
                    D = '0' + D;
                }
                if (H < 10) {
                    H = '0' + H;
                }
                if (Min < 10) {
                    Min = '0' + Min;
                }
                if (S < 10) {
                    S = '0' + S;
                }
                return Y + '-' + M + '-' + D + '  ' + H + ':' + Min + ':' + S;
            },

            init(id) {
                let _this = this;
                this.$nextTick(() => {
                    let vm = this;
                    let height = document.body.offsetHeight - 300;
                    tinymce.init({
                        selector: ('#' + id),
                        branding: false,
                        elementpath: false,
                        height: height,
                        language: 'zh_CN.GB2312',
                        menubar: 'edit insert view format table tools',
                        plugins: [
                            'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                            'searchreplace visualblocks visualchars code fullpage',
                            'insertdatetime media nonbreaking save table contextmenu directionality',
                            'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                        ],
                        toolbar1: ' newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                        autosave_interval: '20s',
                        image_advtab: true,
                        table_default_styles: {
                            width: '100%',
                            borderCollapse: 'collapse'
                        },
                        setup: function (editor) {
                            editor.on('init', function (e) {
                                if (_this.formData[id]) {
                                    tinymce.get(id).setContent(_this.formData[id]);
                                }
                            });
                            editor.on('change', function (e) {
                                _this.formData[id] = tinymce.get(id).getContent();
                            });
                        }
                    });
                });
            },
            destroyed() {
                this.saveModalVisible = false
            },
            handleSuccess (res, file) {
                this.uploadList = [{
                    showProgress: true,
                    percentage: 0
                }]
                let interval = setInterval(() => {
                    this.uploadList[0].percentage += 2;
                    if (this.uploadList[0].percentage === 100) {
                        clearInterval(interval);
                    }
                }, 100);
                setTimeout(() => {
                    this.$Notice.success({
                        title: '文件上传成功',
                        desc: '文件 ' + file.name + ' 上传成功。',
                        duration: 2
                    });
                    file.url = CONSTANTS.SERVER_HOST + res.data.imgUrl;
                    file.name = res.data.fileName;
                    this.uploadList = this.$refs.upload.fileList;
                    this.formData.cover = res.data.imgUrl;
                    this.imgUrl = res.data.imgUrl;
                }, 5000);
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请选择图片文件。',
                    duration: 5
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                    duration: 5
                });
            },
            handleRemove (file) {
                this.uploadList = [];
                this.$refs.upload.fileList = [];
                this.formData.cover = '';
            },
            handleBeforeUpload () {
                const check = this.uploadList.length < 1;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多只能上传 1 张图片。',
                        duration: 5
                    });
                }
                return check;
            },
            refresh(){
                this.queryCon = {
                    inputTime:'',
                   name:'',
                    id:'',
                    introduce:'',

                };
                this.loadList();
            },
            setPrice(id){
                this.priceModalVisible = true;
                this.activityId = id;
                let _this = this;
                util.ajax.post('/busine/price/listByActivity', util.toFormData({
                    id: id
                })).then(res => {
                    if(res.data.data){
                        _this.priceList = res.data.data;
                        if(_this.priceList.length == 0){
                            _this.priceList.splice(0, 0, {
                                name:'',
                                money:''
                            });
                        }
                    }
                })
            },
            addPrice(){
                const price = {
                    name:'',
                    money:''
                };
                const priceList = this.priceList;
                this.priceList.splice(priceList.length, 0, price);
            },
            delPrice(){
                const priceList = this.priceList;
                if(priceList.length>0){
                    this.priceList.splice(priceList.length-1, 1);
                }
                if(priceList.length==0){
                    this.priceList.splice(0, 0, {
                        name:'',
                        money:''
                    });
                }
            },
            priceSave(){
                let _this = this;
                let priceList = [];
                for(let i=0 ; i<_this.priceList.length ; i++){
                    if(_this.priceList[i].name!="" && _this.priceList[i].money!=""){
                        priceList.splice(priceList.length-1,0,_this.priceList[i]);
                    }
                }
                util.ajax.post('/busine/price/saveByActivity', util.toFormData({
                    id:_this.activityId,
                    listStr:JSON.stringify(priceList)
                })).then(res => {
                    if (res.data.message === 'SUCCESS') {
                        this.saveModalVisible = false;
                        this.$Message.success('保存成功！');
                        this.pageIndex = 1;
                        this.loadList();
                    } else {
                        this.$Message.warning(res.data.message || '未知错误！');
                    }
                });
                this.priceModalVisible = false;
            },
            priceCancel(){
                this.priceModalVisible = false;
            },
            issue(id){
                let _this = this;
                util.ajax.post('/busine/price/listByActivity', util.toFormData({
                    id: id
                })).then(res => {
                    let priceData = res.data.data
                    let sumPrice = 0;
                    for(let i=0 ; i<priceData.length ; i++){
                        sumPrice += priceData[i].money;
                    }
                    if(sumPrice == 0){
                        _this.$Modal.confirm({
                            title: '警告',
                            content: '未设置价格，是否继续发布！',
                            okText:'继续',
                            onOk: () => {
                                util.ajax.post('/busine/activity/issue', util.toFormData({
                                    id: id
                                })).then(res => {
                                    if (res.data.message === 'SUCCESS') {
                                        this.$Message.success('发布成功！');
                                        this.pageIndex = 1;
                                        this.loadList();
                                    } else {
                                        this.$Message.warning(res.data.message || '未知错误！');
                                    }
                                })
                            }
                        });
                    }else{
                        util.ajax.post('/busine/activity/issue', util.toFormData({
                            id: id
                        })).then(res => {
                            if (res.data.message === 'SUCCESS') {
                                this.$Message.success('发布成功！');
                                this.pageIndex = 1;
                                this.loadList();
                            } else {
                                this.$Message.warning(res.data.message || '未知错误！');
                            }
                        })
                    }
                })
            },
            teacherSelect(value){
                this.formData.ledteacher = value
                let list = this.ledTeacherList.filter(item => item.name.indexOf(value) > -1);
                if(list.length==0){
                    this.isSelect = false;
                    this.isInput = true;
                    this.formData.ledteacherId = '';
                }
            },
            teacherInput(data){
                if(!(data.data)){
                    this.isSelect = true;
                    this.isInput = false;
                }
            },
            openImg(){
                this.showImg = true;
            },
            closeImg(){
                this.showImg = false;
            },
            openImgDetail(){
                this.showImgDetail = true;
            },
            closeImgDetail(){
                this.showImgDetail = false;
            }
        }
    };
</script>
